<?php

namespace yak\layui\search;

use Kordar\Excel\DataListExcelOutputBehavior;
use Kordar\Excel\OutputExcelEvent;
use yak\layui\helper\YakHelper;
use yak\layui\models\Menu;
use yak\layui\widgets\grid\LayuiActionColumn;
use yak\layui\widgets\grid\LayuiCheckColumn;
use yak\layui\widgets\grid\LayuiSerialColumn;
use yak\layui\traits\OutputExcelTrait;
use yak\layui\traits\SearchTrait;
use yii\base\Model;
use yii\data\ActiveDataProvider;

/**
 * MenuSearch represents the model behind the search form of `yak\layui\models\Menu`.
 */
class MenuSearch extends Menu implements LayuiSearchInterface, LayuiOutputSearchInterface
{
    use SearchTrait, OutputExcelTrait;

    public function behaviors()
    {
        return [
            'output-excel' => [
                'class' => DataListExcelOutputBehavior::class,
                'template' => \Yii::getAlias('@Kordar/Excel/default.xlsx'),
                'filename' => '菜单列表.xlsx'
            ]
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id', 'pid', 'pos', 'active', 'sort', 'status'], 'integer'],
            [['title', 'href', 'language', 'icon'], 'safe'],
            [['yak_lst', 'yak_lst_txt', 'yak_lst_ext', 'yak_dt', 'yak_dt_s', 'yak_dt_e'], 'safe'],
            [['date_s', 'date_e', 'date_sel', 'yak_output_excel'], 'safe']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Menu::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params, '');

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        if (!empty($this->yak_dt_s) && !empty($this->yak_dt_e)) {
            $this->yak_dt_e = date('Y-m-d', strtotime('+1 day', strtotime($this->yak_dt_e)));
            $query->andFilterWhere(['between', $this->yak_dt, $this->yak_dt_s, $this->yak_dt_e]);
        }

        if (!empty($this->yak_lst)) {

            if ($this->yak_lst_ext == 'EQ') {
                $query->andFilterWhere([$this->yak_lst => $this->yak_lst_txt]);
            }

            if ($this->yak_lst_ext == 'LIKE') {
                $query->andFilterWhere(['like', $this->yak_lst, $this->yak_lst_txt]);
            }
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'pid' => $this->pid,
            'pos' => $this->pos,
            'active' => $this->active,
            'sort' => $this->sort,
            'status' => $this->status,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'href', $this->href])
            ->andFilterWhere(['like', 'language', $this->language])
            ->andFilterWhere(['like', 'icon', $this->icon]);

        if ($this->yak_output_excel === '1') {
            ini_set('memory_limit', '1024M');
            $this->trigger(DataListExcelOutputBehavior::EVENT_OUTPUT_EXCEL, new OutputExcelEvent([
                'dataProvider' => $dataProvider,
                'maxRow' => 20000,
                'columns' => $this->outputColumns()
            ]));
        }

        return $dataProvider;
    }

    /**
     * @return array
     */
    public function columns(): array
    {
        return [
            [
                'class' => LayuiCheckColumn::class
            ],
            [
                'class' => LayuiSerialColumn::class,
                'options' => [
                    'colOptions' => [
                        'width' => 60,
                    ]
                ],
            ],
            [
                'attribute' => 'id',
                'options' => [
                    'colOptions' => [
                        'hide' => true,
                        // 'sort' => true
                    ]
                ],
            ],
            [
                'attribute' => 'title',
                'options' => [
                    'colOptions' => [
                        'edit' => 'text',
                        'sort' => true
                    ]
                ]
            ],
            [
                'attribute' => 'href',
                'options' => [
                    'colOptions' => [
                        'edit' => 'text',
                        'sort' => true
                    ]
                ]
            ],
            [
                'attribute' => 'pos',
                'options' => [
                    'colOptions' => [
                        'width' => 100
                    ]
                ],
                'format' => ['selected', $this->posLabels()]
            ],
            [
                'attribute' => 'pid',
                'format' => ['selected', YakHelper::generateTreeByData(Menu::menuData([0, 1, 2]))]
            ],
            [
                'attribute' => 'icon',
                'options' => [
                    'colOptions' => [
                        'width' => 60,
                    ]
                ],
                'format' => 'layuiIcon'
            ],
            [
                'attribute' => 'sort',
                'options' => [
                    'colOptions' => [
                        'edit' => 'text',
                        'sort' => true
                    ]
                ],
            ],
            [
                'attribute' => 'active',
                'format' => ['selected', \Yii::$app->params['yes.and.no']],
                'options' => [
                    'colOptions' => [
                        'edit' => 'radio',
                        'event' => "active"
                    ]
                ]
            ],
            // 'created_at:datetime',
            // 'updated_at:datetime',
            [
                'class' => LayuiActionColumn::class,
                'toolbar' => '#tool',
                'options' => [
                    'colOptions' => [
                        'width' => 180,
                    ]
                ],
            ]
        ];
    }

    public function outputColumns(): array
    {
        // TODO: Implement outputColumns() method.
        return [
            'id',
            'title'
        ];
    }

    /**
     * @return array
     */
    public function limits(): array
    {
        // TODO: Implement limits() method.
        return [10, 20, 50, 100];
    }

    /**
     * @return int
     */
    public function pageSize(): int
    {
        // TODO: Implement pageSize() method.
        return 15;
    }
}
